package cn.com.headfree.base.initData;

import cn.com.headfree.base.service.SysDictionaryInfoService;
import cn.com.headfree.depterprela.service.OrgDeptService;
import cn.com.headfree.entity.TOrgDept;
import cn.com.headfree.vo.SysDictionaryInfoVo;
import com.alibaba.fastjson.JSONObject;
import com.gta.edu.sdk.util.EhCacheUtil;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.context.WebApplicationContext;
import java.util.*;

public class InitData {
	private static int dictionaryTime;
	@Value("${redis.dictionary.timelong}")
	public void setDictionaryTime(int dictionaryTime) {
		this.dictionaryTime = dictionaryTime;
	}
	private static InitData instance;
	private static final org.apache.logging.log4j.Logger LOG = LogManager.getLogger(InitData.class);
	
	private InitData() {
	}

	public static InitData getInstance() {
		synchronized (InitData.class) {
			if (instance == null) {
				instance = new InitData();
			}
			return instance;
		}
	}
	
	public void initData(WebApplicationContext app) {
		try {
			LOG.info("************初始化机构开始******************");
			initDeptData(app);
			LOG.info("************初始化机构完成******************");
		} catch (Exception e) {
			LOG.info("************初始化机构失败******************", e);
		}
//		LOG.info("************初始化数据字典开始******************");
//		try {
//			initSysDictionary(app);
//			LOG.info("************初始化数据字典完成******************");
//		} catch (Exception e) {
//			LOG.info("************初始化数据字典失败******************", e);
//		}
	}


	private void initDeptData(WebApplicationContext app) {
		OrgDeptService orgDeptService = (OrgDeptService) app.getBean("orgDeptService");
		// 获取所有的部门信息
		List<TOrgDept> allDepts = orgDeptService.findAll();
		//存入redis
//		RedisClusterUtil.getInstance().setString("org-dept-info-", JSONObject.toJSONString(allDepts), dictionaryTime);
		EhCacheUtil.put("org-dept-info-", JSONObject.toJSONString(allDepts));
	}

	private void initSysDictionary(WebApplicationContext app) {
		SysDictionaryInfoService sysDictionaryInfoService = (SysDictionaryInfoService) app.getBean("sysDictionaryInfoService");
		Map<String, List<SysDictionaryInfoVo>> codeMap = new HashMap<String, List<SysDictionaryInfoVo>>();
		List<SysDictionaryInfoVo> dictList = sysDictionaryInfoService.getSysDictionaryInfo("6d81ed6c864046ffb564e78912ab2c10");
		for (SysDictionaryInfoVo code : dictList) {
			List<SysDictionaryInfoVo> entityList = sysDictionaryInfoService.getSysDictionaryInfo(code.getId());
			codeMap.put(code.getValue(), entityList);
		}
		//放入缓存
		if (codeMap != null) {
			EhCacheUtil.put("sysdictionary-info-", JSONObject.toJSONString(codeMap));
		}
	}


}
